import React, { useState } from 'react';
import { useNavigate, Link as RouterLink } from 'react-router-dom';
import {
  Container,
  Box,
  Typography,
  TextField,
  Button,
  Card,
  CardContent,
  Alert,
  CircularProgress,
  Link,
  Grid,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio
} from '@mui/material';
import { PersonAddOutlined } from '@mui/icons-material';
import { validateEmail } from '../utils/validation';
import { apiRequest } from '../utils/api';

const Register = () => {
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    confirmPassword: '',
    firstName: '',
    lastName: '',
    role: 'USER'
  });
  const [errors, setErrors] = useState({});
  const [serverError, setServerError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));

    // 清除对应字段的验证错误
    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: null
      }));
    }
  };

  const validateForm = () => {
    const newErrors = {};

    // 邮箱验证
    if (!formData.email) {
      newErrors.email = '请输入电子邮箱';
    } else if (!validateEmail(formData.email)) {
      newErrors.email = '请输入有效的电子邮箱地址';
    }

    // 姓名验证
    if (!formData.firstName) {
      newErrors.firstName = '请输入名字';
    }

    if (!formData.lastName) {
      newErrors.lastName = '请输入姓氏';
    }

    // 密码验证
    if (!formData.password) {
      newErrors.password = '请输入密码';
    } else if (formData.password.length < 6) {
      newErrors.password = '密码长度至少为6个字符';
    }

    // 确认密码验证
    if (!formData.confirmPassword) {
      newErrors.confirmPassword = '请确认密码';
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setServerError('');

    // 表单验证
    if (!validateForm()) {
      return;
    }

    setLoading(true);

    try {
      const userData = {
        email: formData.email,
        password: formData.password,
        firstName: formData.firstName,
        lastName: formData.lastName,
        role: formData.role
      };
      
      const apiUrl = '/api/auth/register';
      console.log('Sending registration request to:', apiUrl);
      console.log('Request data:', userData);
      
      const response = await apiRequest.post(apiUrl, userData);
      
      console.log('Registration response:', response.data);
      
      // 注册成功，存储令牌和用户信息
      const { token, user } = response.data;
      localStorage.setItem('token', token);
      localStorage.setItem('userInfo', JSON.stringify(user));
      
      setSuccessMessage('注册成功！即将跳转到首页...');
      setTimeout(() => {
        navigate('/');
      }, 2000);

    } catch (err) {
      console.error('Registration error details:', err);
      setServerError(
        err.response?.data?.error || 
        err.message ||
        '注册失败，请稍后重试'
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container maxWidth="sm">
      <Box sx={{ mt: 8, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <Card sx={{ width: '100%', mb: 4 }}>
          <CardContent sx={{ p: 4 }}>
            <Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
              <PersonAddOutlined color="primary" sx={{ fontSize: '40px' }} />
            </Box>
            <Typography component="h1" variant="h5" align="center" gutterBottom>
              创建账户
            </Typography>
            <Typography component="p" variant="subtitle1" align="center" gutterBottom sx={{ color: 'text.secondary', fontStyle: 'italic' }}>
              选择您的角色权限
            </Typography>

            {serverError && (
              <Alert severity="error" sx={{ mb: 3 }}>{serverError}</Alert>
            )}

            {successMessage && (
              <Alert severity="success" sx={{ mb: 3 }}>{successMessage}</Alert>
            )}

            <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
              <Grid container spacing={2}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    margin="normal"
                    required
                    fullWidth
                    id="firstName"
                    label="名字"
                    name="firstName"
                    autoComplete="given-name"
                    value={formData.firstName}
                    onChange={handleChange}
                    error={!!errors.firstName}
                    helperText={errors.firstName}
                    disabled={loading || successMessage}
                  />
                </Grid>
                <Grid item xs={12} sm={6}>
                  <TextField
                    margin="normal"
                    required
                    fullWidth
                    id="lastName"
                    label="姓氏"
                    name="lastName"
                    autoComplete="family-name"
                    value={formData.lastName}
                    onChange={handleChange}
                    error={!!errors.lastName}
                    helperText={errors.lastName}
                    disabled={loading || successMessage}
                  />
                </Grid>
              </Grid>
              
              <TextField
                margin="normal"
                required
                fullWidth
                id="email"
                label="电子邮箱"
                name="email"
                type="email"
                autoComplete="email"
                value={formData.email}
                onChange={handleChange}
                error={!!errors.email}
                helperText={errors.email}
                disabled={loading || successMessage}
              />
              
              <TextField
                margin="normal"
                required
                fullWidth
                name="password"
                label="密码"
                type="password"
                id="password"
                autoComplete="new-password"
                value={formData.password}
                onChange={handleChange}
                error={!!errors.password}
                helperText={errors.password || '密码长度至少为6个字符'}
                disabled={loading || successMessage}
              />
              
              <TextField
                margin="normal"
                required
                fullWidth
                name="confirmPassword"
                label="确认密码"
                type="password"
                id="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleChange}
                error={!!errors.confirmPassword}
                helperText={errors.confirmPassword}
                disabled={loading || successMessage}
              />

              <FormControl component="fieldset" sx={{ mt: 2, mb: 1, width: '100%' }}>
                <FormLabel component="legend">选择角色</FormLabel>
                <RadioGroup
                  row
                  name="role"
                  value={formData.role}
                  onChange={handleChange}
                >
                  <FormControlLabel 
                    value="USER" 
                    control={<Radio />} 
                    label="普通用户" 
                  />
                  <FormControlLabel 
                    value="SERVICE_PROVIDER" 
                    control={<Radio />} 
                    label="服务商" 
                  />
                  <FormControlLabel 
                    value="ADMIN" 
                    control={<Radio />} 
                    label="管理员" 
                  />
                </RadioGroup>
              </FormControl>

              <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                {formData.role === 'ADMIN' 
                  ? '管理员：拥有系统全部权限，可查看所有车辆数据'
                  : '普通用户：可绑定车辆并查看个人车辆数据'}
              </Typography>

              <Button
                type="submit"
                fullWidth
                variant="contained"
                sx={{ mt: 3, mb: 2 }}
                disabled={loading || successMessage}
                startIcon={loading ? <CircularProgress size={20} color="inherit" /> : null}
              >
                {loading ? '注册中...' : '注册账户'}
              </Button>
              
              <Grid container justifyContent="center" sx={{ mt: 2 }}>
                <Grid item>
                  <Typography variant="body2">
                    已有账户?{' '}
                    <RouterLink to="/login" style={{ textDecoration: 'none' }}>
                      <Link variant="body2">立即登录</Link>
                    </RouterLink>
                  </Typography>
                </Grid>
              </Grid>
            </Box>
          </CardContent>
        </Card>
      </Box>
    </Container>
  );
};

export default Register;